package com.yuan.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuan.pojo.dto.UserResponse;
import com.yuan.pojo.vo.UserRequestVo;
import com.yuan.service.UserRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/*
 *  @author 雨安
 *  类名： APIController
 *  创建时间：2024/3/15
 */
@RestController
@RequestMapping("/axd")
public class APIController {
    //装配Service层
    @Autowired
    UserRequestService userRequestService;

    @PostMapping("/AddUser")
    public ResponseEntity<UserResponse> addUser(@RequestBody(required = false) String json) throws NoSuchAlgorithmException, JsonProcessingException {
        //判断不为null
        if (json!=null && json.trim().length()!=0){
            try{
                //拿到数据转换对象
                ObjectMapper mapper = new ObjectMapper();
                //转换json格式数据映射到UserRequestVo类
                UserRequestVo trainingData = mapper.readValue(json, UserRequestVo.class);
                //判断是否转换成功
                if (trainingData!=null && trainingData.toString().trim().length()!=0){
                    //将json的md5解密hash得到  此处加密是使用json的data数据加密
                    String md5Hash = getMd5Hash(trainingData.getData().toString());
                    //判断数据是否完整
                    if (trainingData.getSign() != null && trainingData.getSign().equals(md5Hash)){
                        //执行添加方法
                        boolean b = userRequestService.saveBatch(trainingData.getData());
                        //判断是否执行成功
                        if (b == true){
                            //执行添加成功
                            return ResponseEntity.ok(new UserResponse(0, "数据录入成功", ""));
                        }else {
                            //执行添加失败
                            return ResponseEntity.ok(new UserResponse(-1, "数据录入失败", ""));
                        }
                    }else{
                        //判断后数据并不是完整的
                        return ResponseEntity.ok(new UserResponse(-2,"MD5校验失败,数据疑似被攻击",""));
                    }
                }
            }catch (Exception e){
                return ResponseEntity.ok(new UserResponse(-3,"转换出现异常",""));
            }
        }
        return ResponseEntity.ok(new UserResponse(-4,"传递的json数据为null",""));
    }

//    public static void main(String[] args) throws IOException {
//        //创建url请求
//        URL url = new URL("https://risk.cqxingxun.com/risk/tongji/xuexi");
//        //打开url连接
//        HttpURLConnection con = (HttpURLConnection) url.openConnection();
//        //设置请求方式
//        con.setRequestMethod("GET");
//        //设置响应编码
//        con.setRequestProperty("Content-Type", "application/json");
//        //开启参数发送
//        con.setDoOutput(true);
//        //设置参数  此处MD5为使用 ObjectMapper 对象将json中的data取出映射到Vo层集合中在将集合toString()进行的md5解密
//        String jsonData = "{\"timestamp\" : \"1513738930081\",\"sign\":\"65a8e27d8879283831b664bd8b7f0ad4\",\"year\":\"2023\",\"month\":\"12\",\"data\" : [{\"name\" : \"哈哈哈\",\"company\" : \" 企业名称3\",\"idNumber\" : \"500112198603154125\",\"phone\" : \"17326501205\",\"learningTime\" : 180,\"completeStatus\" : \"已完成\"},{\"name\" : \"zsh测试数据2\",\"company\" : \"企业名称2\",\"idNumber\" : \"500112198603154125\",\"phone\" : \"17326501205\",\"learningTime\" : 180,\"completeStatus\" : \"已完成\"}]}\n";
//        //创建output流
//        OutputStream os = con.getOutputStream();
//        //设置字符集
//        byte[] input = jsonData.getBytes("utf-8");
//        //写出去
//        os.write(input, 0, input.length);
//        //获取响应码
//        con.getResponseCode();
//        //读取响应内容
//        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
//
//        String inputLine;
//        //使用buffer接收string字符串
//        StringBuffer response = new StringBuffer();
//        //遍历
//        while ((inputLine = in.readLine()) != null) {
//            //循环打印数据
//            response.append(inputLine);
//        }
//        //关闭流
//        in.close();
//        //打印测试
//        System.out.println(response);
//    }


    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
        //创建url请求
        URL url = new URL("https://risk.cqxingxun.com/risk/tongji/xuexi");
        //打开url连接
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //设置请求方式
        con.setRequestMethod("POST");
        //设置响应编码
        con.setRequestProperty("Content-Type", "application/json");
        //开启参数发送
        con.setDoOutput(true);
        //设置参数  此处MD5为使用 ObjectMapper 对象将json中的data取出映射到Vo层集合中在将集合toString()进行的md5解密  a5214111c0dd0716c62dfe969cc2f68f  318dcfb0e128566996527c7bf3b1094c
//        String jsonData = "{\"timestamp\" : \"1513738930081\",\"sign\":\"8e022f4d8bb30a6c1684dc9656e4a512\",\"year\":\"2023\",\"month\":\"12\",\"data\" : [{\"name\" : \"哈哈哈\",\"company\" : \" 企业名称3\",\"idNumber\" : \"500112198603154125\",\"phone\" : \"17326501205\",\"learningTime\" : 180,\"completeStatus\" : \"已完成\"},{\"name\" : \"zsh测试数据2\",\"company\" : \"企业名称2\",\"idNumber\" : \"500112198603154125\",\"phone\" : \"17326501205\",\"learningTime\" : 180,\"completeStatus\" : \"已完成\"}]}\n";
        String jsonData = "{\"timestamp\" : \"1513738930081\",\"sign\":\"a5214111c0dd0716c62dfe969cc2f68f\",\"year\":\"2023\",\"month\":\"12\",\"data\" : [{\"name\" : \"吴用\",\"company\" : \" 企业名称1\",\"idNumber\" : \"500112198603154125\",\"phone\" : \"17326501205\",\"learningTime\" : 180,\"completeStatus\" : \"已完成\",\"studyPlatform\":\"驾运宝\",\"orgCode\":\"1234567890\"},{\"name\" : \"张锋\",\"company\" : \"企业名称2\",\"idNumber\" : \"500112198603154125\",\"phone\" : \"17326501205\",\"learningTime\" : 180,\"completeStatus\" : \"已完成\",\"studyPlatform\":\"驾安通\",\"orgCode\":\"X234567890\"}]}";
        //映射
        ObjectMapper objectMapper = new ObjectMapper();
        //映射
        UserRequestVo userRequestVo = objectMapper.readValue(jsonData, UserRequestVo.class);
        System.out.println(userRequestVo.getData() + "这是我转换的数据");
        getMd5Hash(userRequestVo.getData().toString() + "这是我的md5密钥");

        //创建output流
        OutputStream os = con.getOutputStream();
        //设置字符集
        byte[] input = jsonData.getBytes("utf-8");
        //写出去
        os.write(input, 0, input.length);
        //获取响应码
        con.getResponseCode();
        //读取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        //使用buffer接收string字符串
        StringBuffer response = new StringBuffer();
        //遍历
        while ((inputLine = in.readLine()) != null) {
            //循环打印数据
            response.append(inputLine);
        }
        //关闭流
        in.close();
        //打印测试
        System.out.println(response);
    }


    public static String getMd5Hash(String input) throws NoSuchAlgorithmException {
        //创建MessageDigest实例
        MessageDigest md = MessageDigest.getInstance("MD5");
        //将待解密的字符转换为字节数组
        byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
        //计算MD5摘要
        byte[] digestBytes = md.digest(inputBytes);
        //将字节数组转换为16禁止字符串
        StringBuilder sb = new StringBuilder();
        //遍历
        for (byte b:digestBytes) {
            sb.append(String.format("%02x",b));
        }
        //解密的Hash值
        String md5 = sb.toString();
        System.out.println(md5);
        //返回解密的值
        return md5;
    }


}
